package com.example.zkweixiu.app.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.example.zkweixiu.app.R;
import com.example.zkweixiu.app.bean.DefaultUser;
import com.example.zkweixiu.app.bean.MyMessage;
import com.example.zkweixiu.app.model.Imdata;
import com.example.zkweixiu.app.myview.ChatView;
import com.example.zkweixiu.app.pro.PublicPro;
import com.littlegreens.netty.client.NettyTcpClient;
import com.littlegreens.netty.client.listener.MessageStateListener;
import com.littlegreens.netty.client.listener.NettyClientListener;
import com.yanzhenjie.sofia.Sofia;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.joda.time.DateTime;
import org.litepal.LitePal;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import cn.jiguang.imui.chatinput.ChatInputView;

import cn.jiguang.imui.chatinput.listener.OnMenuClickListener;
import cn.jiguang.imui.chatinput.model.FileItem;
import cn.jiguang.imui.commons.ImageLoader;
import cn.jiguang.imui.commons.models.IMessage;
import cn.jiguang.imui.commons.models.IUser;
import cn.jiguang.imui.messages.MsgListAdapter;
import cn.jiguang.imui.messages.ViewHolderController;
import cn.jiguang.imui.messages.ptr.PtrHandler;
import cn.jiguang.imui.messages.ptr.PullToRefreshLayout;

/**
 * 聊天详情
 */
public class IMsgActivity extends AppCompatActivity implements View.OnTouchListener, SensorEventListener {
    private Imdata imdata;
    public NettyTcpClient mNettyTcpClient;
    List<MyMessage> list = new ArrayList<>();
    private ImageLoader imageLoader;
    public volatile  Map<String, MyMessage> msg_list = new ConcurrentHashMap<String, MyMessage>();
    private final static String TAG = "MessageListActivity";
    private final int RC_RECORD_VOICE = 0x0001;
    private final int RC_CAMERA = 0x0002;
    private final int RC_PHOTO = 0x0003;

    private ChatView mChatView;
    private MsgListAdapter<MyMessage> mAdapter;
    private List<MyMessage> mData;
  //  private HeadsetDetectReceiver mReceiver;
    private InputMethodManager mImm;
    private Window mWindow;
    private SensorManager mSensorManager;
    private Sensor mSensor;
    private PowerManager mPowerManager;
    private PowerManager.WakeLock mWakeLock;
/*    private class HeadsetDetectReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
                if (intent.hasExtra("state")) {
                    int state = intent.getIntExtra("state", 0);
                    mAdapter.setAudioPlayByEarPhone(state);
                }
            }
        }
    }*/

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_imsg);
        Sofia.with(IMsgActivity.this).statusBarDarkFont().statusBarBackground(Color.parseColor("#F0F0F0"));

        initView();
      //  PendingIntent.getService()
        connectService();
        /*MessageList messageList = (MessageList) findViewById(R.id.msg_list);
        ChatInputView chat_input =  findViewById(R.id.chat_input);
        chat_input.setOnTouchListener(this);

        initMsgAdapter();
        MsgListAdapter.HoldersConfig holdersConfig = new MsgListAdapter.HoldersConfig();
        MsgListAdapter  mAdapter = new MsgListAdapter<>("0", holdersConfig, imageLoader);
        messageList.setHasFixedSize(true);
        MyMessage message = new MyMessage("Hello World", IMessage.MessageType.RECEIVE_TEXT.ordinal());
        message.setUserInfo(new DefaultUser("0", "Deadpool", "R.drawable.deadpool"));

        mAdapter.addToStart(message, true);

        Resources res = getResources();

        String[] messages = res.getStringArray(R.array.conversation);
        for (int i = 0; i < messages.length; i++) {
            MyMessage thisms;
            if (i % 2 == 0) {

                thisms = new MyMessage(messages[i], IMessage.MessageType.RECEIVE_TEXT.ordinal());
                thisms.setUserInfo(new DefaultUser("0", "DeadPool", "R.drawable.deadpool"));
            } else {
                thisms = new MyMessage(messages[i], IMessage.MessageType.SEND_TEXT.ordinal());
                thisms.setUserInfo(new DefaultUser("1", "IronMan", "R.drawable.ironman"));
            }
            thisms.setTimeString(new SimpleDateFormat("HH:mm", Locale.getDefault()).format(new Date()));
            thisms.setMessageStatus(IMessage.MessageStatus.SEND_SUCCEED);
            list.add(thisms);
           // messageList.getPtrLayout
        }

        mAdapter.addToEndChronologically(list);

        messageList.setAdapter(mAdapter);
        mAdapter.getLayoutManager().scrollToPosition(0);

        mAdapter.setAudioPlayByEarPhone(0);*/


    }

    private void connectService() {
        mNettyTcpClient = new NettyTcpClient.Builder()
                .setHost(PublicPro.SERVICE_TCP)    //设置服务端地址
                .setTcpPort(8192) //设置服务端端口号
                .setMaxReconnectTimes(5)    //设置最大重连次数
                .setReconnectIntervalTime(5)    //设置重连间隔时间。单位：秒
                .setSendheartBeat(true) //设置发送心跳
                .setHeartBeatInterval(30)    //设置心跳间隔时间。单位：秒
                .setHeartBeatData("00@#&_&%&") //设置心跳数据，可以是String类型，也可以是byte[]，以后设置的为准
                .setIndex(1032)    //设置客户端标识.(因为可能存在多个tcp连接)
                .build();


        mNettyTcpClient.setListener(new NettyClientListener() { //注册监听事件
            @Override
            public void onMessageResponseClient(Object msg, int index) {
                String ponse = msg.toString();
                //    Log.e("onMessageResponseClient", ponse);


                if (ponse.contains("STATUS_6I6S6@_@%#")) {
                    String[] split = ponse.split("@_@%#",2);

                    if (split[1].contains("ERR")) {
                        String err = split[1].replace("ERR", "");
                        MyMessage myMessage = msg_list.get(err);
                        myMessage.setMessageStatus(IMessage.MessageStatus.SEND_FAILED);

                        mAdapter.updateMessage(myMessage);

                        msg_list.remove(err);
                    }else {

                        Log.e("onMessageResponseClient", "次数");
                        MyMessage myMessage = msg_list.get(split[1]);
                        myMessage.setMessageStatus(IMessage.MessageStatus.SEND_SUCCEED);



                        long millis = new DateTime().getMillis(); //获取当前系统时间戳
                        Imdata imdata2 = new Imdata();
                        IUser fromUser = myMessage.getFromUser();
                       // thisms.setUserInfo(new DefaultUser("1", "IronMan", "R.drawable.ironman"));
                        imdata2.setMy_uuid(PublicPro.userBean.getData().getGuaUuid());
                        imdata2.setIs_send("1");
                        imdata2.setIm_img(fromUser.getAvatarFilePath());
                        imdata2.setIm_name(fromUser.getDisplayName());
                        imdata2.setIm_uuid(PublicPro.userBean.getData().getGuaUuid());
                        imdata2.setIm_msg(myMessage.getText());
                        imdata2.setIm_time(millis);
                        imdata2.save();
                        PublicPro.NEWS_MSG = imdata2;
                        mAdapter.updateMessage(myMessage);

                        msg_list.remove(split[1]);

                        return;
                    }
            /*        if ("ERR".equals()) {

                    }*/
                }
/*                    else if ("200".equals(ponse)){
                        EventBus.getDefault().post(ponse);
                    }*/

            }

            @Override
            public void onClientStatusConnectChanged(int statusCode, int index) {
                Log.e("setListener", String.valueOf(statusCode));
            }
        });
        mNettyTcpClient.connect();


    }

    @SuppressLint("ClickableViewAccessibility")
    private void initView() {
        this.mImm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        mWindow = getWindow();
        registerProximitySensorListener();
        mChatView = (ChatView) findViewById(R.id.chat_view);
        mChatView.initModule();
        mChatView.setTitle("中凯交流群");
    //    mData = getMessages();
        initMsgAdapter();
       // mReceiver = new HeadsetDetectReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_HEADSET_PLUG);
     //  registerReceiver(mReceiver, intentFilter);
        mChatView.setOnTouchListener(this);



        MsgListAdapter.HoldersConfig holdersConfig = new MsgListAdapter.HoldersConfig();
        mAdapter = new MsgListAdapter<>("0", holdersConfig, imageLoader);


        mChatView.getChatInputView().getInputView().setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                scrollToBottom();
                return false;
            }
        });

        mChatView.getSelectAlbumBtn().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(IMsgActivity.this, "OnClick select album button", Toast.LENGTH_SHORT).show();

            }
        });


        PullToRefreshLayout layout = mChatView.getPtrLayout();
        layout.setPtrHandler(new PtrHandler() {  //下拉加载数据
            @Override
            public void onRefreshBegin(PullToRefreshLayout layout) {
              //  Log.i("MessageListActivity", "Loading next page");
                Toast.makeText(IMsgActivity.this, "没有更多记录了", Toast.LENGTH_SHORT).show();
                mChatView.getPtrLayout().refreshComplete();
             //   loadNextPage();
            }
        });

        mChatView.setMenuClickListener(new OnMenuClickListener() {
            @Override
            public boolean onSendTextMessage(CharSequence input) {  //消息发送
                if (input.length() == 0) {
                    return false;
                }

                try {
                    sendMsg(input.toString());
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    Toast.makeText(IMsgActivity.this, "发送失败", Toast.LENGTH_SHORT).show();
                }


                //  scrollToBottom();
                return true;
            }

            @Override
            public void onSendFiles(List<FileItem> list) {
                if (list == null || list.isEmpty()) {
                    return;
                }
                // should reset messageList height
                mChatView.setMsgListHeight(true);

            }

            @Override
            public boolean switchToMicrophoneMode() {
                scrollToBottom();

                return true;
            }

            @Override
            public boolean switchToGalleryMode() {
                scrollToBottom();

                // If you call updateData, select photo view will try to update data(Last update over 30 seconds.)
                mChatView.getChatInputView().getSelectPhotoView().updateData();
                return true;
            }

            @Override
            public boolean switchToCameraMode() {
                scrollToBottom();

                return true;
            }

            @Override
            public boolean switchToEmojiMode() {
                scrollToBottom();
                return true;
            }
        });

/*        Resources res = getResources();
        String[] messages = res.getStringArray(R.array.conversation);*/



/*        for (int i = 0; i < messages.length; i++) {
            MyMessage thisms;
            if (i % 2 == 0) {

                thisms = new MyMessage(messages[i], IMessage.MessageType.RECEIVE_TEXT.ordinal());
                thisms.setUserInfo(new DefaultUser("0", "DeadPool", "R.drawable.deadpool"));
            } else {
                thisms = new MyMessage(messages[i], IMessage.MessageType.SEND_TEXT.ordinal());
                thisms.setUserInfo(new DefaultUser("1", "IronMan", "R.drawable.ironman"));
            }
            thisms.setTimeString(new SimpleDateFormat("HH:mm", Locale.getDefault()).format(new Date()));
            thisms.setMessageStatus(IMessage.MessageStatus.SEND_SUCCEED);
            list.add(thisms);
            // messageList.getPtrLayout
        }

        mAdapter.addToEndChronologically(list);*/


        List<Imdata> newsList = LitePal.where("my_uuid = ?", PublicPro.userBean.getData().getGuaUuid()).find(Imdata.class);
        Log.e("onMessageResponseClient",newsList.size()+"//////////");

        Collections.reverse(newsList);

        Log.e("onMessageResponseClient",newsList.size()+"//////////");
        if (newsList == null || newsList.size() == 0) {
        }else {
            List<MyMessage> list = new ArrayList<>();
/*            Resources res = getResources();
            String[] messages = res.getStringArray(R.array.conversation);*/
            for (Imdata imdata : newsList) {
                MyMessage message;
                if ("1".equals(imdata.getIs_send())) {
                     message = new MyMessage(imdata.getIm_msg(), IMessage.MessageType.SEND_TEXT.ordinal());
                    message.setUserInfo(new DefaultUser("1",imdata.getIm_name(), imdata.getIm_img()));
                    message.setMessageStatus(IMessage.MessageStatus.SEND_SUCCEED);
                }else {
                    message = new MyMessage(imdata.getIm_msg(), IMessage.MessageType.RECEIVE_TEXT.ordinal());
                    message.setUserInfo(new DefaultUser("0",imdata.getIm_name(), imdata.getIm_img()));
                }
                list.add(message);

            }

            mAdapter.addToEndChronologically(list);
            mChatView.getPtrLayout().refreshComplete();


        }


        mChatView.setAdapter(mAdapter);
        mAdapter.getLayoutManager().scrollToPosition(0);


    }

    /**
     * 消息发送
     * */
    private void sendMsg(String msg) throws UnsupportedEncodingException {
        if (mNettyTcpClient == null){
            Toast.makeText(this, "正在连接聊天服务器请稍后...", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!mNettyTcpClient.getConnectStatus()) {//没有连接 连接
            mNettyTcpClient.connect();
            Toast.makeText(this, "连接断开尝试正在尝试重新连接...", Toast.LENGTH_SHORT).show();
            return;
        }

        MyMessage message = new MyMessage(msg, IMessage.MessageType.SEND_TEXT.ordinal());
        message.setUserInfo(new DefaultUser("1", PublicPro.userBean.getData().getGuaName(), "http://111.61.64.62:8001/group1/M00/00/01/wKgZhV3krh2AaPVDAAQqKpbszHg957.jpg"));
        //  message.setTimeString(new SimpleDateFormat("HH:mm", Locale.getDefault()).format(new Date()));
        message.setMessageStatus(IMessage.MessageStatus.SEND_GOING);
        mAdapter.addToStart(message, true);


        String concat = "MSG_IM@_@%#".concat("http://111.61.64.62:8001/group1/M00/00/01/wKgZhV3krh2AaPVDAAQqKpbszHg957.jpg").concat("@_@%#").concat(PublicPro.userBean.getData().getGuaName())
                .concat("@_@%#").concat(PublicPro.userBean.getData().getGuaUuid()).concat("@_@%#").concat(msg).concat("@_@%#").concat(message.getMsgId()).concat("@#&_&%&");
        Log.e("CLI_SET",concat);

        mNettyTcpClient.sendMsgToServer(concat.getBytes("UTF-8"), new MessageStateListener() {
            @Override
            public void isSendSuccss(boolean isSuccess) {
                if (isSuccess) {
                    Log.e("isSuccess", "send successful");
                } else {
                    Log.e("isSuccess", "设备离线");
                }
            }
        });

        msg_list.put(message.getMsgId(),message); //设置未返回成功的消息

    }


    private void loadNextPage() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                List<MyMessage> list = new ArrayList<>();
                Resources res = getResources();
                String[] messages = res.getStringArray(R.array.conversation);
                for (int i = 0; i < messages.length; i++) {
                    MyMessage message;
                    if (i % 2 == 0) {
                        message = new MyMessage(messages[i], IMessage.MessageType.RECEIVE_TEXT.ordinal());
                        message.setUserInfo(new DefaultUser("0", "DeadPool", "R.drawable.deadpool"));
                    } else {
                        message = new MyMessage(messages[i], IMessage.MessageType.SEND_TEXT.ordinal());
                        message.setUserInfo(new DefaultUser("1", "IronMan", "R.drawable.ironman"));
                    }
                    message.setTimeString(new SimpleDateFormat("HH:mm", Locale.getDefault()).format(new Date()));
                    list.add(message);
                }
//                Collections.reverse(list);
                // MessageList 0.7.2 add this method, add messages chronologically.
                mAdapter.addToEndChronologically(list);
                mChatView.getPtrLayout().refreshComplete();
            }
        }, 1500);
    }
    private void scrollToBottom() {
        mChatView.setMsgListHeight(false);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mChatView.getMessageListView().smoothScrollToPosition(0);
            }
        }, 200);
    }

    @SuppressLint("InvalidWakeLockTag")
    private void registerProximitySensorListener() {
        try {
            mPowerManager = (PowerManager) getSystemService(POWER_SERVICE);
            mWakeLock = mPowerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, TAG);
            mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
            mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
            mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initMsgAdapter() {
        final float density = getResources().getDisplayMetrics().density;
        final float MIN_WIDTH = 60 * density;
        final float MAX_WIDTH = 200 * density;
        final float MIN_HEIGHT = 60 * density;
        final float MAX_HEIGHT = 200 * density;
        imageLoader = new ImageLoader() {
            @Override
            public void loadAvatarImage(ImageView avatarImageView, String string) {
                // You can use other image load libraries.
                if (string.contains("R.drawable")) {
                    Integer resId = getResources().getIdentifier(string.replace("R.drawable.", ""),
                            "drawable", getPackageName());

                    avatarImageView.setImageResource(resId);
                } else {
                    Glide.with(getApplicationContext())
                            .load(string)
                            .apply(new RequestOptions().placeholder(R.drawable.aurora_headicon_default))
                            .into(avatarImageView);
                }
            }

            /**
             * Load image message
             * @param imageView Image message's ImageView.
             * @param string A file path, or a uri or url.
             */
            @Override
            public void loadImage(final ImageView imageView, String string) {
                // You can use other image load libraries.
                Glide.with(getApplicationContext())
                        .asBitmap()
                        .load(string)
                        .apply(new RequestOptions().fitCenter().placeholder(R.drawable.aurora_picture_not_found))
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(@NonNull Bitmap resource, @Nullable com.bumptech.glide.request.transition.Transition<? super Bitmap> transition) {
                                int imageWidth = resource.getWidth();
                                int imageHeight = resource.getHeight();
                                //     Log.d(TAG, "Image width " + imageWidth + " height: " + imageHeight);

                                // 裁剪 bitmap
                                float width, height;
                                if (imageWidth > imageHeight) {
                                    if (imageWidth > MAX_WIDTH) {
                                        float temp = MAX_WIDTH / imageWidth * imageHeight;
                                        height = temp > MIN_HEIGHT ? temp : MIN_HEIGHT;
                                        width = MAX_WIDTH;
                                    } else if (imageWidth < MIN_WIDTH) {
                                        float temp = MIN_WIDTH / imageWidth * imageHeight;
                                        height = temp < MAX_HEIGHT ? temp : MAX_HEIGHT;
                                        width = MIN_WIDTH;
                                    } else {
                                        float ratio = imageWidth / imageHeight;
                                        if (ratio > 3) {
                                            ratio = 3;
                                        }
                                        height = imageHeight * ratio;
                                        width = imageWidth;
                                    }
                                } else {
                                    if (imageHeight > MAX_HEIGHT) {
                                        float temp = MAX_HEIGHT / imageHeight * imageWidth;
                                        width = temp > MIN_WIDTH ? temp : MIN_WIDTH;
                                        height = MAX_HEIGHT;
                                    } else if (imageHeight < MIN_HEIGHT) {
                                        float temp = MIN_HEIGHT / imageHeight * imageWidth;
                                        width = temp < MAX_WIDTH ? temp : MAX_WIDTH;
                                        height = MIN_HEIGHT;
                                    } else {
                                        float ratio = imageHeight / imageWidth;
                                        if (ratio > 3) {
                                            ratio = 3;
                                        }
                                        width = imageWidth * ratio;
                                        height = imageHeight;
                                    }
                                }
                                ViewGroup.LayoutParams params = imageView.getLayoutParams();
                                params.width = (int) width;
                                params.height = (int) height;
                                imageView.setLayoutParams(params);
                                Matrix matrix = new Matrix();
                                float scaleWidth = width / imageWidth;
                                float scaleHeight = height / imageHeight;
                                matrix.postScale(scaleWidth, scaleHeight);
                                imageView.setImageBitmap(Bitmap.createBitmap(resource, 0, 0, imageWidth, imageHeight, matrix, true));
                            }

              /*          @Override
                        public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {

                        }*/
                        });
            }

            /**
             * Load video message
             * @param imageCover Video message's image cover
             * @param uri Local path or url.
             */
            @Override
            public void loadVideo(ImageView imageCover, String uri) {
                long interval = 5000 * 1000;
                Glide.with(getApplicationContext())
                        .asBitmap()
                        .load(uri)
                        // Resize image view by change override size.
                        .apply(new RequestOptions().frame(interval).override(200, 400))
                        .into(imageCover);
            }
        };

    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        switch (motionEvent.getAction()) {
            case MotionEvent.ACTION_DOWN:
                ChatInputView chatInputView = mChatView.getChatInputView();
                if (chatInputView.getMenuState() == View.VISIBLE) {
                    chatInputView.dismissMenuLayout();
                }
                mChatView.setMsgListHeight(true);
                try {
                    View v = getCurrentFocus();
                    if (mImm != null && v != null) {
                        mImm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                        mWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
                        view.clearFocus();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case MotionEvent.ACTION_UP:
                view.performClick();
                break;
        }
        return false;
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        try {
            if (audioManager.isBluetoothA2dpOn() || audioManager.isWiredHeadsetOn()) {
                return;
            }
            if (mAdapter.getMediaPlayer().isPlaying()) {
                float distance = event.values[0];
                if (distance >= mSensor.getMaximumRange()) {
                    mAdapter.setAudioPlayByEarPhone(0);
                    setScreenOn();
                } else {
                    mAdapter.setAudioPlayByEarPhone(2);
                    ViewHolderController.getInstance().replayVoice();
                    setScreenOff();
                }
            } else {
                if (mWakeLock != null && mWakeLock.isHeld()) {
                    mWakeLock.release();
                    mWakeLock = null;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }


    private void setScreenOn() {
        if (mWakeLock != null) {
            mWakeLock.setReferenceCounted(false);
            mWakeLock.release();
            mWakeLock = null;
        }
    }

    @SuppressLint("InvalidWakeLockTag")
    private void setScreenOff() {
        if (mWakeLock == null) {
            mWakeLock = mPowerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, TAG);
        }
        mWakeLock.acquire();
    }


    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);

    }

    @Override
    public void onStop() {
        super.onStop();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        PublicPro.MSG_COUNT = 0;
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onMessageEvent(Imdata event) {
        if (event != null){
            MyMessage message = new MyMessage(event.getIm_msg(), IMessage.MessageType.RECEIVE_TEXT.ordinal());
            message.setUserInfo(new DefaultUser("0",event.getIm_name(), event.getIm_img()));
            mAdapter.addToStart(message, true);
        }

    }
}
